package bfa.playlist_importer_exporter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

public class ImportPlaylist {

	private static final String NAME = "name";
	 
	 public static final String TAG = "MediaUtil";

	  public static void deleteTrack(Context context, String localPath) {
	    Uri uri = MediaStore.Audio.Media.getContentUriForPath(localPath);
	    context.getContentResolver().delete(uri, null, null);
	  }

	  public static Cursor query(Context context, Uri uri, String[] projection,
	      String selection, String[] selectionArgs, String sortOrder, int limit) {
	    try {
	      ContentResolver resolver = context.getContentResolver();
	      if (resolver == null) {
	        return null;
	      }
	      if (limit > 0) {
	        uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
	      }
	      return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
	    } catch (UnsupportedOperationException ex) {
	      Log.e("IMP",ex.toString());
	      return null;
	    }
	  }

	  public static Cursor query(Context context, Uri uri, String[] projection,
	      String selection, String[] selectionArgs, String sortOrder) {
	    return query(context, uri, projection, selection, selectionArgs, sortOrder, 0);
	  }

	  private static int intFromCursor(Cursor c) {
	    int id = -1;
	    if (c != null) {
	      c.moveToFirst();
	      if (!c.isAfterLast()) {
	        id = c.getInt(0);
	      }
	    }
	    c.close();
	    return id;
	  }

	  public static int idForplaylist(Context context, String name) {
	    Cursor c = query(context, MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
	        new String[] { MediaStore.Audio.Playlists._ID },
	        NAME + "=?",
	        new String[] { name },
	        NAME);
	    return intFromCursor(c);
	  }

	  public static int idFortrack(Context context, String path) {
	    Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
	        new String[] { MediaStore.Audio.Media._ID },
	        "_data" + "=?",
	        new String[] { path },
	        "_data");
	    return intFromCursor(c);
	  }
	 
	 
	 public static Playlist writePlaylist(Context context, String playlistName, ArrayList<String> paths) {
		 Playlist risultato=new Playlist();
		    ContentResolver resolver = context.getContentResolver();
		    int playlistId = idForplaylist(context, playlistName);
		    Uri uri;
		    if (playlistId == -1) { 
		      ContentValues values = new ContentValues(1);
		      values.put(NAME, playlistName);
		      Log.d(TAG, String.format("Creating playlist %s", playlistName));
		      uri = resolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values);
		      playlistId = idForplaylist(context, playlistName);
		    } else {
		      uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId); 
		    }
		    
		    uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
		    
		    risultato.id=playlistId;
		    risultato.name=playlistName;
		    
		    Log.d(TAG, String.format("Writing playlist %s", uri));
		    
		    // Delete everything from the old playlist
		    context.getContentResolver().delete(uri, null, null);

		    // Add all the new tracks to the playlist.
		    int size = paths.size();
		    
		    for (int k = 0; k < size; ++k) {
	    		  ContentValues values = new ContentValues(1);
				  values = new ContentValues();
				  values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, k);
				  values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, idFortrack(context, paths.get(k)));
		      
				  Uri uri2 = resolver.insert(uri, values);
				  Log.d(TAG, String.format("Writing song %s", uri2));

		      
		    }
		    

		    
		    return risultato;
		    
		    
		  }	 
	
	 public static ArrayList<Playlist> importPlaylists(Context context,File fileToImport) {
		 //ArrayList<Playlist> playlists=new ArrayList<Playlist>();
		 if (fileToImport.exists()) {
		
			 
			//Read text from file
			 StringBuilder text = new StringBuilder();

			 try {
			     BufferedReader br = new BufferedReader(new FileReader(fileToImport));
			     String line;

			     while ((line = br.readLine()) != null) {
			         text.append(line);
			         text.append('\n');
			     }
			     
			     
			     try {
						JSONObject j=new JSONObject(text.toString());
						
						JSONArray playlistsj=j.getJSONArray("playlists");
						for (int t=0;t<playlistsj.length();t++) {
							JSONObject playlist=playlistsj.getJSONObject(t);
							
							
							ArrayList<String> percorsi=new ArrayList<String>();
							JSONArray songs=playlist.getJSONArray("songs");
							for (int s=0;s<songs.length();s++) {
								JSONObject song=songs.getJSONObject(s);
								percorsi.add(song.getString("_data"));
									
							}
							
							writePlaylist(context, playlist.getString("name"),percorsi);
							//playlists.add(p);
						}
						
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
					 
			 }
			 catch (IOException e) {
			     //You'll need to add proper error handling here
			 }
			 

		 }
		 
		 return ExportPlaylist.getPlayLists(context);
		 
	 }
	 
}
